﻿var g_url = "http://www.baimashu.com.cn/";
// var g_url = "http://168.168.168.240:8088/";
// var g_url = "http://168.168.168.111:6060/";
var rootWin = "";
// 等待队列
var loadingQueue = 0;
// 融云 AppKey
var rongcloudAppKey = "m7ua80gbuuf8m";
// 融云 AppSecret
var rongcloudAppSecret = "cEtE8VhfMQvT3";

/**
 *
 * 获取跟窗口。
 *
 */
function getRootWin() {
    return $api.getStorage("rootWin");
}

/**
 *
 * 获取性别。
 *
 * @return {string} 性别
 *
 */
function getGender() {
    var info = getLoginUserInfo();

    if (isObject(info)) {
        if (info.GENDER == "1") {
            return "男";
        } else {
            return "女";
        }
    }

    return "";
}

/**
 *
 * 获取全局唯一标识，32 位 GUID。
 *
 * @return {string} 全局唯一标识，32 位 GUID
 *
 */
function getGUID() {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }

    return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4()).toUpperCase();
}

/**
 *
 * 获取全局唯一标识，32 位 UUID。
 *
 * @return {string} 全局唯一标识，32 位 UUID
 *
 */
function getUUID() {
    var d = new Date().getTime();

    var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;

        d = Math.floor(d / 16);

        return (c == "x" ? r : (r & 0x3 | 0x8)).toString(16);
    });

    return uuid.replaceAll("-", "").toUpperCase();
}

/**
 *
 * 获取时间戳，不包含毫秒。
 *
 * @return {number} 时间戳，不包含毫秒
 *
 */
function getTimestampNoMillisecond() {
    return Math.floor(getTimestamp() / 1000);
}

/**
 *
 * 上传文件。
 *
 * @param actid ACT ID
 * @param localPath 本地路径
 * @param remotePath 远程路径，作文件名称使用
 * @param getintro
 * @param isLoading 是否显示等待框
 * @param func 回调函数
 *
 */
function uploadFile(actId, localPath, remotePath, getintro, isLoading, func) {
    if (isEmpty(actId) || isEmpty(localPath) || isEmpty(remotePath) || isEmpty(getintro) || isNull(isLoading) || !isFunction(func)) {
        return;
    }

    remotePath = (remotePath + "." + getFileSuffix(localPath));

    var posturl = g_url + "mobileupload.do?requesttype=activity&path=" + actId + "&filename=" + remotePath + "&time=" + getTimestamp();

    if (isLoading) {
        loadingQueue++;

        if (loadingQueue == 1) {
            /*
             api.showProgress({
             title: "",
             text: "",
             modal: false
             });
             */

            $.myLoading("show");
        }
    }

    api.ajax({
        url: posturl,
        method: "post",
        timeout: 30,
        dataType: "json",
        returnAll: false,
        headers: {
            "Content-Type": "text/x-markdown"
        },
        data: {
            files: {
                file: localPath
            },
            stream: localPath
        }
    }, function (ret, err) {
        if (isLoading) {
            loadingQueue--;

            if (loadingQueue <= 0) {
                loadingQueue = 0;

                // api.hideProgress();

                $.myLoading("hide");
            }
        }

        // 请求成功
        if (isObject(ret)) {
            // 上传文件出错
            if (ret.statusCode != 0) {
                toast("上传文件出错");
            }

            func(ret, null, remotePath, getintro);

            // 请求失败
        } else {
            toast(err.msg);

            func(null, err, null, null);
        }
    });
}

/**
 *
 * 上传头像。
 *
 * @param staffId 用户 ID
 * @param localPath 本地路径
 * @param remotePath 远程路径，作文件名称使用
 * @param isLoading 是否显示等待框
 * @param func 回调函数
 *
 */
function uploadHeadImage(staffId, localPath, remotePath, isLoading, func) {
    if (isEmpty(staffId) || isEmpty(localPath) || isEmpty(remotePath) || isNull(isLoading) || !isFunction(func)) {
        return;
    }

    remotePath = (remotePath + "." + getFileSuffix(localPath));

    var posturl = g_url + "mobileupload.do?requesttype=headimg&path=" + staffId + "&filename=" + remotePath + "&time=" + getTimestamp();

    if (isLoading) {
        loadingQueue++;

        if (loadingQueue == 1) {
            /*
             api.showProgress({
             title: "",
             text: "",
             modal: false
             });
             */

            $.myLoading("show");
        }
    }

    api.ajax({
        url: posturl,
        method: "post",
        timeout: 30,
        dataType: "json",
        returnAll: false,
        headers: {
            "Content-Type": "text/x-markdown"
        },
        data: {
            files: {
                file: localPath
            },
            stream: localPath
        }
    }, function (ret, err) {
        if (isLoading) {
            loadingQueue--;

            if (loadingQueue <= 0) {
                loadingQueue = 0;

                // api.hideProgress();

                $.myLoading("hide");
            }
        }

        // 请求成功
        if (isObject(ret)) {
            // 上传头像出错
            if (ret.statusCode != 0) {
                toast("上传头像出错");
            }

            func(ret, null, remotePath);

            // 请求失败
        } else {
            toast(err.msg);

            func(null, err, null);
        }
    });
}
/**
 * 上传作业图片
 * @param studentId
 * @param localPath
 * @param remotePath
 * @param isLoading
 * @param func
 */
function uploadWorkImage(studentId, localPath, remotePath, isLoading, func) {

    if (isEmpty(studentId) || isEmpty(localPath) || isEmpty(remotePath) || isNull(isLoading) || !isFunction(func)) {
        return;
    }

    remotePath = (remotePath + "." + getFileSuffix(localPath));

    var posturl = g_url + "mobileupload.do?requesttype=workimg&path=" + studentId + "&filename=" + remotePath + "&time=" + getTimestamp();

    if (isLoading) {
        loadingQueue++;

        if (loadingQueue == 1) {
            /*
             api.showProgress({
             title: "",
             text: "",
             modal: false
             });
             */

            $.myLoading("show");
        }
    }

    api.ajax({
        url: posturl,
        method: "post",
        timeout: 30,
        dataType: "json",
        returnAll: false,
        headers: {
            "Content-Type": "text/x-markdown"
        },
        data: {
            files: {
                file: localPath
            },
            stream: localPath
        }
    }, function (ret, err) {
        if (isLoading) {
            loadingQueue--;

            if (loadingQueue <= 0) {
                loadingQueue = 0;

                // api.hideProgress();

                $.myLoading("hide");
            }
        }

        // 请求成功
        if (isObject(ret)) {
            // 上传头像出错
            if (ret.statusCode != 0) {
                toast("上传图片出错");
            }

            func(ret, null, remotePath);

            // 请求失败
        } else {
            toast(err.msg);

            func(null, err, null);
        }
    });
}

/**
 * 上传意见图片
 * @param studentId
 * @param localPath
 * @param remotePath
 * @param isLoading
 * @param func
 */
function uploadAdviseImage(studentPhone, localPath, remotePath, isLoading, func) {

    if (isEmpty(studentPhone) || isEmpty(localPath) || isEmpty(remotePath) || isNull(isLoading) || !isFunction(func)) {
        return;
    }

    remotePath = (remotePath + "." + getFileSuffix(localPath));

    var posturl = g_url + "mobileupload.do?requesttype=adviseimg&path=" + studentPhone + "&filename=" + remotePath + "&time=" + getTimestamp();

    if (isLoading) {
        loadingQueue++;

        if (loadingQueue == 1) {
            /*
             api.showProgress({
             title: "",
             text: "",
             modal: false
             });
             */

            $.myLoading("show");
        }
    }

    api.ajax({
        url: posturl,
        method: "post",
        timeout: 30,
        dataType: "json",
        returnAll: false,
        headers: {
            "Content-Type": "text/x-markdown"
        },
        data: {
            files: {
                file: localPath
            },
            stream: localPath
        }
    }, function (ret, err) {
        if (isLoading) {
            loadingQueue--;

            if (loadingQueue <= 0) {
                loadingQueue = 0;

                // api.hideProgress();

                $.myLoading("hide");
            }
        }

        // 请求成功
        if (isObject(ret)) {
            // 上传头像出错
            if (ret.statusCode != 0) {
                toast("上传图片出错");
            }

            func(ret, null, remotePath);

            // 请求失败
        } else {
            toast(err.msg);

            func(null, err, null);
        }
    });
}

/**
 *
 * 数据查询。
 *
 * @param curPage 当前页
 * @param pageSize 页码
 * @param sql 数据查询 SQL
 * @param isLoading 是否显示等待框
 * @param func 回调函数
 *
 */
function dbQuery(curPage, pageSize, sql, isLoading, func) {
    if (!isNumber(curPage) || !isNumber(pageSize) || isEmpty(sql) || isNull(isLoading) || !isFunction(func)) {
        return;
    }

    if (curPage != 0) {
        sql = sql + " LIMIT " + (curPage - 1) * pageSize + "," + pageSize;
    }
    var posturl = g_url + "mobilequery.do?time=" + getTimestamp();
    var postdata = {
        pageSize: 0,
        currentPage: curPage,
        statement: sql,
        params: null
    };
    var poststr = $api.jsonToStr(postdata);

    if (isLoading) {
        loadingQueue++;

        if (loadingQueue == 1) {
            /*
             api.showProgress({
             title: "",
             text: "",
             modal: false
             });
             */

            $.myLoading("show");
        }
    }

    api.ajax({
        url: posturl,
        method: "post",
        cache: true,
        timeout: 15,
        dataType: "json",
        headers: {
            "Content-Type": "application/json"
        },
        data: {
            body: poststr
        }
    }, function (ret, err) {
        if (isLoading) {
            loadingQueue--;

            if (loadingQueue <= 0) {
                loadingQueue = 0;

                // api.hideProgress();

                $.myLoading("hide");
            }
        }

        // 请求成功
        if (isObject(ret)) {
            // 查询出错
            if (ret.statusCode != 0) {
                toast("查询出错");
            }

            func(ret, null);

            // 请求失败
        } else {
            toast(err.msg);

            func(null, err);
        }
    });
}

/**
 *
 * 数据执行。
 *
 * @param sql 数据执行 SQL
 * @param isLoading 是否显示等待框
 * @param func 回调函数
 *
 */
function dbExecute(sql, isLoading, func) {
    if (isEmpty(sql) || isNull(isLoading) || !isFunction(func)) {
        return;
    }

    var posturl = g_url + "mobileexecute.do?time=" + getTimestamp();
    var postdata = {
        statement: sql,
        params: null
    };
    var poststr = $api.jsonToStr(postdata);

    if (isLoading) {
        loadingQueue++;

        if (loadingQueue == 1) {
            /*
             api.showProgress({
             title: "",
             text: ""
             });
             */

            $.myLoading("show");
        }
    }

    api.ajax({
        url: posturl,
        method: "post",
        cache: true,
        timeout: 15,
        dataType: "json",
        headers: {
            "Content-Type": "application/json"
        },
        data: {
            body: poststr
        }
    }, function (ret, err) {
        if (isLoading) {
            loadingQueue--;

            if (loadingQueue <= 0) {
                loadingQueue = 0;

                // api.hideProgress();

                $.myLoading("hide");
            }
        }

        // 请求成功
        if (isObject(ret)) {
            // 执行出错
            if (ret.statusCode != 0) {
                toast("执行出错");
            }

            func(ret, null);

            // 请求失败
        } else {
            toast(err.msg);

            func(null, err);
        }
    });
}

/**
 *
 * 收藏。
 *
 * @param el
 * @param type
 *
 */
function collect(el, type) {
    var uid = $api.getStorage("uid");
    //login
    if (!uid) {
        api.openWin({
            name: "userLogin",
            url: "./userLogin.html",
            opaque: true,
            vScrollBarEnabled: false
        });
        return;
    }

    //news id, activity id, merchant id
    var thisId = $api.attr(el, "news-id") || $api.attr(el, "act-id") || $api.attr(el, "mer-id");

    var userFavUrl = "/user/" + uid + "/" + type;
    var bodyParam = {};
    switch (type) {
        case "act_fav":
            bodyParam["activity"] = thisId;
            break;
        case "news_fav":
            bodyParam["news"] = thisId;
            break;
        case "mer_fav":
            bodyParam["merchant"] = thisId;
            break;
    }
    ajaxRequest(userFavUrl, "post", JSON.stringify(bodyParam), function (ret, err) {
        if (ret) {
            $api.html(el, "已收藏");
            $(el).off("click").on("click", function () {
                uncollect(type, ret.id, this);
            })
        } else {
            api.toast({
                msg: "收藏失败"
            })
        }
    })
}

/**
 *
 * 取消收藏。
 *
 * @param _class
 * @param id
 * @param el
 *
 */
function uncollect(_class, id, el) {
    try {
        var deleteAct_favById = "/" + _class + "/" + id;
        ajaxRequest(deleteAct_favById, "delete", "", function (ret, err) {
            if (ret) {
                $api.html(el, "收藏");
                $(el).off("click").on("click", function () {
                    collect(this, _class);
                })
            } else {
                api.toast({
                    msg: "操作失败"
                })
            }
        })
    } catch (e) {
        alert(e)
    }

}

/**
 *
 * SHA1 算法。
 *
 * @param msg 被加密的文本
 * @return {*} 加密后的文本
 *
 */
function SHA1(msg) {
    if (isEmpty(msg)) {
        return null;
    }

    function rotate_left(n, s) {
        var t4 = (n << s ) | (n >>> (32 - s));
        return t4;
    };

    function lsb_hex(val) {
        var str = "";
        var i;
        var vh;
        var vl;

        for (i = 0; i <= 6; i += 2) {
            vh = (val >>> (i * 4 + 4)) & 0x0f;
            vl = (val >>> (i * 4)) & 0x0f;
            str += vh.toString(16) + vl.toString(16);
        }
        return str;
    };

    function cvt_hex(val) {
        var str = "";
        var i;
        var v;

        for (i = 7; i >= 0; i--) {
            v = (val >>> (i * 4)) & 0x0f;
            str += v.toString(16);
        }
        return str;
    };

    function Utf8Encode(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    };

    var blockstart;
    var i, j;
    var W = new Array(80);
    var H0 = 0x67452301;
    var H1 = 0xEFCDAB89;
    var H2 = 0x98BADCFE;
    var H3 = 0x10325476;
    var H4 = 0xC3D2E1F0;
    var A, B, C, D, E;
    var temp;

    msg = Utf8Encode(msg);

    var msg_len = msg.length;

    var word_array = new Array();
    for (i = 0; i < msg_len - 3; i += 4) {
        j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 | msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3);
        word_array.push(j);
    }

    switch (msg_len % 4) {
        case 0:
            i = 0x080000000;
            break;
        case 1:
            i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000;
            break;

        case 2:
            i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000;
            break;

        case 3:
            i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80;
            break;
    }

    word_array.push(i);

    while ((word_array.length % 16) != 14)
        word_array.push(0);

    word_array.push(msg_len >>> 29);
    word_array.push((msg_len << 3) & 0x0ffffffff);

    for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {

        for (i = 0; i < 16; i++)
            W[i] = word_array[blockstart + i];
        for (i = 16; i <= 79; i++)
            W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);

        A = H0;
        B = H1;
        C = H2;
        D = H3;
        E = H4;

        for (i = 0; i <= 19; i++) {
            temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        for (i = 20; i <= 39; i++) {
            temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        for (i = 40; i <= 59; i++) {
            temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        for (i = 60; i <= 79; i++) {
            temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        H0 = (H0 + A) & 0x0ffffffff;
        H1 = (H1 + B) & 0x0ffffffff;
        H2 = (H2 + C) & 0x0ffffffff;
        H3 = (H3 + D) & 0x0ffffffff;
        H4 = (H4 + E) & 0x0ffffffff;

    }

    var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);

    return temp.toLowerCase();

}

function ajaxRequest(url, method, bodyParam, callBack) {
    var common_url = "https://d.apicloud.com/mcm/api";
    var appId = "A6963429484030";
    var key = "7F836F04-CAAC-52C8-2332-CF337134FA6F";
    var now = Date.now();
    var appKey = SHA1(appId + "UZ" + key + "UZ" + now) + "." + now;
    api.ajax({
        url: common_url + url,
        method: method,
        cache: false,
        timeout: 20,
        headers: {
            "Content-type": "application/json;charset=UTF-8",
            "X-APICloud-AppId": appId,
            "X-APICloud-AppKey": appKey
        },
        data: {
            body: bodyParam
        }
    }, function (ret, err) {
        callBack(ret, err);
    });
}

function myajaxReq(url, method, bodyParam, callBack) {
    var common_url = "https://d.apicloud.com/mcm/api";
    var appId = "A6997842522344";
    var key = "F37CFEA5-A208-5D81-E96D-C8FC105AC7AE";
    var now = Date.now();
    var appKey = SHA1(appId + "UZ" + key + "UZ" + now) + "." + now;
    api.ajax({
        url: common_url + url,
        method: method,
        cache: false,
        timeout: 20,
        headers: {
            "Content-type": "application/json;charset=UTF-8",
            "X-APICloud-AppId": appId,
            "X-APICloud-AppKey": appKey
        },
        data: {
            body: bodyParam
        }
    }, function (ret, err) {
        callBack(ret, err);
    });
}

function SaveToMysql(DebugVal) {
    api.ajax({
        url: "http://192.168.10.103:8080/antsclub/user/register",
        method: "post",
        cache: false,
        timeout: 30,
        dataType: "json",
        data: {
            values: {
                uname: "",
                pwd: "",
                content: DebugVal
            }
        }
    }, function (ret, err) {
        if (ret) {
            //				api.toast({msg:ret.msg});
        } else {
            api.toast({
                msg: ("错误码：" + err.code + "；错误信息：" + err.msg + "网络状态码：" + err.statusCode)
            });
        }
        ;
    });
}

function execPageList(opt, call) {
    var page = opt.page;
    api.ajax({
        url: g_url + "queryJson.do?a=b",
        method: "post",
        cache: false,
        timeout: 30,
        dataType: "json",
        data: {
            values: {
                remote_args: {
                    "queryId": page.queryId,
                    "currentPage": page.currentPage,
                    "pageSize": page.pageSize,
                    "sortExpr": page.sortExpr,
                    "valueMap": opt.valueMap,
                    "showErrors": "true"
                }
            }
        }
    }, function (ret, err) {
        call(ret, err);
    });
}

/**
 *
 * 执行服务。
 *
 * @param opt 参数
 * @param call 回调函数
 *
 */
function exeService(opt, call) {
    api.ajax({
        url: g_url + "callJson.do?a=b",
        method: "post",
        cache: false,
        timeout: 30,
        dataType: "json",
        data: {
            values: {
                remote_args: opt
            }
        }
    }, function (ret, err) {
        call(ret, err);
    });
}

/**
 *
 * 弹出警告框。
 *
 * @param msg 消息
 * @param func 回调函数
 *
 */
function systemAlert(msg, func) {
    api.confirm({
        title: "系统提示",
        msg: strmsg
    }, function (ret, err) {
        if (ret.buttonIndex == 2) {
            func();
        }
    });
}

/**
 *
 * 吐司消息提示。
 *
 * @param msg 消息
 *
 */
function toast(msg) {
    if (isNotEmpty(msg)) {
        api.toast({
            msg: msg,
            duration: 2000,
            location: "bottom"
        });
    }
}

/**
 *
 * 发送短信。
 *
 * @param mobile 手机号
 * @param content 短信内容
 * @param msgId 消息 ID
 * @param func 回调函数
 *
 */
function sendSms(mobile, content, msgId, func) {
    var strurl = "http://webservice.hctcom.com/service.asmx/SendSMS?uc=carycao&pwd=nicholas&callee=" + mobile
        + "&cont=" + content + "&msgid=" + msgId + "&otime=";
    api.ajax({
        url: strurl,
        method: "get",
        cache: false,
        timeout: 30,
        dataType: "json",
        headers: {
            "Content-Type": "text/plain;charset=UTF-8"
        },
        data: {
            body: ""
        }
    }, function (ret, err) {
        func(ret, err);
    });
}

/**
 *
 * 调用 WebService。
 *
 * @param params 参数
 * @param func 回调函数
 *
 */
function callWebService(params, func) {
    var posturl = g_url + "callWebService.do?time=" + getTimestamp();
    var postdata = {
        params: params
    };
    var poststr = $api.jsonToStr(postdata);
    api.ajax({
        url: posturl,
        method: "post",
        cache: false,
        timeout: 30,
        dataType: "json",
        headers: {
            "Content-Type": "application/json"
        },
        data: {
            body: poststr
        }
    }, function (ret, err) {
        func(ret, err);
    });
}

/**
 *
 * 保存信息。
 *
 * @param key 键
 * @param value 值
 *
 */
function setStaffInfo(key, value) {
    if (isEmpty(key) || isNull(value)) {
        return;
    }

    $api.setStorage(key, value);
}

/**
 *
 * 获取信息。
 *
 * @param key 键
 * @return {Object} 值
 *
 */
function getStaffInfo(key) {
    if (isEmpty(key)) {
        return null;
    }

    return $api.getStorage(key);
}

/**
 *
 * 清除所有信息。
 *
 */
function cleanInfo() {
    $api.clearStorage();
}

/**
 *
 * 清除键对应的信息。
 *
 * @param key 键
 *
 */
function removeInfo(key) {
    if (isNotEmpty(key)) {
        $api.rmStorage(key)
    }
}

/**
 *
 * 获取当前时间。
 *
 * @return {string} 当前时间，如：2016-08-26 09:09:23
 *
 */
function getCurrTime() {
    var now = new Date();
    var year = "" + now.getFullYear();
    var month = now.getMonth() + 1;
    if (month < 10) {
        month = "0" + month;
    }

    var day = now.getDate();
    if (day < 10) {
        day = "0" + day;
    }

    var hours = now.getHours();
    if (hours < 10) {
        hours = "0" + hours;
    }

    var minutes = now.getMinutes();
    if (minutes < 10) {
        minutes = "0" + minutes;
    }

    var seconds = now.getSeconds();
    if (seconds < 10) {
        seconds = "0" + seconds;
    }

    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
}

/**
 *
 * 获取当前时间，没有秒。
 *
 * @return {string} 当前时间，如：2016-08-26 09:09:23
 *
 */
function getCurrTimeNoSeconds() {
    var now = new Date();
    var year = "" + now.getFullYear();
    var month = now.getMonth() + 1;
    if (month < 10) {
        month = "0" + month;
    }

    var day = now.getDate();
    if (day < 10) {
        day = "0" + day;
    }

    var hours = now.getHours();
    if (hours < 10) {
        hours = "0" + hours;
    }

    var minutes = now.getMinutes();
    if (minutes < 10) {
        minutes = "0" + minutes;
    }

    return year + "-" + month + "-" + day + " " + hours + ":" + minutes;
}

function getDate(date) {
    var now = date;
    var year = "" + now.getFullYear();
    var month = now.getMonth() + 1;
    if (month < 10) {
        month = "0" + month;
    }

    var day = now.getDate();
    if (day < 10) {
        day = "0" + day;
    }

    var hours = now.getHours();
    if (hours < 10) {
        hours = "0" + hours;
    }

    var minutes = now.getMinutes();
    if (minutes < 10) {
        minutes = "0" + minutes;
    }

    return year + "-" + month + "-" + day;
}

/**
 *
 * 获取字符串实际长度，中文2，英文1。
 *
 * @param str 字符串
 * @return {number} 字符串实际长度
 *
 */
function getStrRealLength(str) {
    if (isEmpty(str)) {
        return 0;
    }

    var realLength = 0, len = str.length, charCode = -1;

    for (var i = 0; i < len; i++) {
        charCode = str.charCodeAt(i);

        if ((charCode >= 0) && (charCode <= 128)) {
            realLength += 1;
        } else {
            realLength += 1;
        }
    }

    return realLength;
}

/**
 *
 * 获取页面数据。
 *
 */
function getFormData() {
    var rtn = new Object();
    // input元素的值
    $("input[type=text]").each(function () {
        var element = $(this);
        if ((element.attr("id") != null) && (element.attr("id") != "")) {
            rtn[element.attr("id")] = element.val();
        }
    });
    $("input[type=hidden]").each(function () {
        var element = $(this);
        if ((element.attr("id") != null) && (element.attr("id") != "")) {
            rtn[element.attr("id")] = element.val();
        }
    });
    // input元素的值
    $("input[type=password]").each(function () {
        var element = $(this);
        if ((element.attr("id") != null) && (element.attr("id") != "")) {
            rtn[element.attr("id")] = element.val();
        }
    });
    // 获取checkbox的值
    $("input[type=checkbox]").each(function () {
        var element = $(this);
        if (element.attr("checked") == true) {
            if ((element.attr("id") != null) && (element.attr("id") != "")) {
                rtn[element.attr("id")] = element.val();

            }
        }

    });
    $("input[type=radio]").each(function () {
        var element = $(this);
        if (element.attr("checked") == true) {
            if ((element.attr("name") != null) && (element.attr("name") != "")) {
                rtn[element.attr("name")] = element.val();
            }
        }
    });
    // 获取textarea的值
    $("textarea").each(function () {
        var element = $(this);
        if ((element.attr("id") != null) && (element.attr("id") != "")) {
            rtn[element.attr("id")] = element.val();
        }
    });
    // 获取select值
    $("select").each(function () {
        var element = $(this);
        if ((element.attr("id") != null) && (element.attr("id") != "")) {
            rtn[element.attr("id")] = element.val();
        }
    });
    return rtn;
}

/**
 *
 * 计算子字符在字符串中出现的次数。
 *
 * @param str 字符串
 * @param subStr 子字符串
 * @return {number} 子字符在字符串中出现的次数
 *
 */
function countSubStr(str, subStr) {
    if (isEmpty(str) || isEmpty(subStr)) {
        return 0;
    }

    // 次数
    var count = 0;
    // 查找时忽略大小写
    var reg = eval("/" + subStr + "/gi");

    if (str.match(reg) == null) {
        count = 0;
    } else {
        count = str.match(reg).length;
    }

    return count;
}

/**
 *
 * 选择对话框。
 *
 */
function comfirmshow(msg, func) {
    api.confirm({
        title: "提示",
        msg: msg,
        buttons: ["确定", "取消"]
    }, function (ret, err) {
        func(ret, err);
    });
}

/**
 *
 * 获取系统类型。
 *
 * @return {*} 系统类型
 *
 */
function getSystemType() {
    return api.systemType;
}

/**
 *
 * 获取 URL。
 *
 * @return {string} URL
 *
 */
function getUrl() {
    return g_url;
}

/**
 *
 * 获取 URL 中的参数。
 *
 * @param url 请求地址
 * @return 参数对象
 *
 */
function getUrlParam(url) {
    if (isEmpty(url)) {
        return null;
    }

    // 获取第一个“?”的索引
    var index = url.indexOf("?");

    // -1 表示 url 没有参数
    if (index === -1) {
        return null;
    }

    // 截取参数字符串
    var paramStr = url.substring(index + 1);

    if (isEmpty(paramStr)) {
        return null;
    }

    // 参数对象
    var paramObj = new Object();
    // 获取参数键值对的数组，如：[p1=1,p2=2,p3=3] 等……
    var params = paramStr.split("&");

    for (var i = 0; i < params.length; i++) {
        var p = params[i];

        if (isNotEmpty(p)) {
            // 参数名称与参数值组成的数组
            var pp = p.split("=");

            if (isNotEmpty(pp[0])) {
                if (isEmpty(pp[1])) {
                    paramObj[pp[0]] = null;
                } else {
                    paramObj[pp[0]] = pp[1];
                }
            }
        }
    }

    return paramObj;
}

/**
 *
 * 获取登录用户信息。
 *
 */
function getLoginUserInfo() {
    var userInfo = getStaffInfo("loginUserInfo");

    if (isObject(userInfo)) {
        return $.extend(true, {}, userInfo)
    } else {
        return null;
    }
}

/**
 *
 * 获取登录学生信息。
 *
 */
function getLoginStudentInfo() {
    var stuInfo = getStaffInfo("loginStudentInfo");

    if (isObject(stuInfo)) {
        return $.extend(true, {}, stuInfo)
    } else {
        return null;
    }
}

/**
 *
 * 获取登录标志。
 *
 */
function getLoginFlag() {
    return getStaffInfo("loginFlag");
}

/**
 *
 * 判断用户是否登录。
 *
 */
function isLogin() {
    if (getLoginFlag() === "true") {
        return true
    }

    return false;
}

/**
 *
 * 跳转至登录界面。
 *
 * @param param 传给登录界面的参数
 *
 */
function toLogin(param) {
    if (!isLogin()) {
        openWin("user-login", "user-login.html", param);
    }
}

/**
 *
 * 退出登录。
 *
 */
function logout() {
    setStaffInfo("loginUserInfo", null);
    setStaffInfo("loginStudentInfo", null);
    setStaffInfo("loginFlag", "false");

    // 发送退出登录事件
    api.sendEvent({
        name: "logoutEvent"
    });
}

/**
 *
 * 打开窗口。
 *
 * @param name 窗口名称
 * @param url 窗口路径
 * @param param 参数
 *
 */
function openWin(name, url, param) {
    if (isEmpty(name)) {
        return;
    }

    if (isEmpty(url)) {
        return;
    }

    if (!isObject(param)) {
        param = {};
    }

    api.openWin({
        name: name,
        url: url,
        pageParam: param,
        opaque: true,
        vScrollBarEnabled: false
    });
}

/**
 *
 * 关闭窗口。
 *
 * @param name 窗口名称。
 *
 */
function closeWin(name) {
    if (isEmpty(name)) {
        api.closeWin();
    } else {
        api.closeWin({name: name});
    }
}

/**
 *
 * 获取所有的城市。
 *
 * @param func 回调函数
 *
 */
function getCitys(func) {
    // 从缓存中获取
    var citys = getStaffInfo("citys");

    // 如果缓存中有
    if (isArray(citys)) {
        // 克隆一个 citys 给回调函数
        func($.extend(true, [], citys));

        // 否则，缓存中没有，则到服务器上获取
    } else {
        var sql = "SELECT T.AREA_CODE, T.SUPER_AREA_CODE, T.PROVINCE, T.CITY ";
        sql += "FROM W_AREA T WHERE (T.CITY_CODE = '00' OR T.COUNTY_CODE = '00') ";
        sql += "AND T.AREA_CODE <> '1102000000' AND T.AREA_CODE <> '1202000000' AND T.AREA_CODE <> '3102000000' AND T.AREA_CODE <> '5002000000' AND T.AREA_CODE <> '5003000000' ";
        sql += "ORDER BY T.PROVINCE_CODE, T.CITY_CODE";

        citys = new Array();

        // 查询所有城市
        dbQuery(1, 500, sql, true, function (ret, err) {
            // 查询成功
            if (isObject(ret) && (ret.statusCode == 0)) {
                // 有数据
                if (isArray(ret.result) && (ret.result.length > 0)) {
                    // 查找出所有的省
                    $.each(ret.result, function (i, r) {
                        if (r.SUPER_AREA_CODE == "0000000000") {
                            var province = new Object();
                            province.AREA_CODE = r.AREA_CODE;
                            province.SUPER_AREA_CODE = r.SUPER_AREA_CODE;
                            province.PROVINCE = r.PROVINCE;
                            province.CITY = r.CITY;
                            province.SUB = new Array();

                            citys.push(province);
                        }
                    });

                    // 查找出省下的市
                    $.each(citys, function (i, c) {
                        $.each(ret.result, function (j, r) {
                            if (c.AREA_CODE == r.SUPER_AREA_CODE) {
                                var city = new Object();
                                city.AREA_CODE = r.AREA_CODE;
                                city.SUPER_AREA_CODE = r.SUPER_AREA_CODE;
                                city.PROVINCE = r.PROVINCE;
                                city.CITY = r.CITY;
                                city.SUB = new Array();

                                c.SUB.push(city);
                            }
                        });
                    });

                    // 整理省级数据
                    $.each(citys, function (i, c) {
                        if (c.SUB.length == 0) {
                            c.CITY = c.PROVINCE;
                        }
                    });

                    // 存入缓存中
                    setStaffInfo("citys", citys);

                    // 克隆一个 citys 给回调函数
                    func($.extend(true, [], citys));

                    // 无数据
                } else {
                    func(null);
                }

                // 查询失败
            } else {
                func(null);
            }
        });
    }
}

/**
 *
 * 清空所有城市。
 *
 */
function clearCitys() {
    removeInfo("citys");
}
////////Duer////////////
/**
 *
 * 加载loading...................
 *
 * $.myLoading("show")显示 $.myLoading("hide")关闭;
 */
(function ($) {
    $.myLoading = function (arg) {
        if (arg == "show") {
            var loadHtml = '<div id="loadWrap"></div>';
            $("body").prepend(loadHtml);
            $("#loadWrap").css({
                "width": "80px",
                "height": "80px",
                "position": "fixed",
                "z-index": "9999",
                "top": "40%",
                "left": "50%",
                "margin-left": "-40px",
                "margin-top": "-40px",
                "background": "url('../images/loading3.gif') no-repeat center center",
                "background-size": "80% 80%"
            });
        } else if (arg == "hide") {
            $("#loadWrap").remove();
        }
    };
})(jQuery);
////////Duer////////////
/**
 *
 * 获取时间戳。
 *
 * @return {number} 时间戳
 *
 */
function getTimestamp() {
    return new Date().getTime();
}

/**
 *
 * 获取 1-1000000 的随机数。
 *
 * @return {number} 随机数
 *
 */
function getRandom() {
    return Math.floor((Math.random() * 1000000) + 1);
}

/**
 *
 * 获取融云 Token。
 *
 * @param userId 用户 ID
 * @param name 用户名称
 * @param portraitUri 用户头像
 * @param func 回调函数
 *
 */
function getRongcloudToken(userId, name, portraitUri, func) {
    var nonce = getRandom() + "";
    var timestamp = getTimestamp() + "";
    var signature = SHA1(rongcloudAppSecret + nonce + timestamp);

    var postData = {
        "userId": userId,
        "name": name,
        "portraitUri": portraitUri
    };

    if (true) {
        loadingQueue++;

        if (loadingQueue == 1) {
            $.myLoading("show");
        }
    }

    api.ajax({
        url: "https://api.cn.ronghub.com/user/getToken.json",
        method: "post",
        cache: false,
        timeout: 30,
        dataType: "json",
        headers: {
            "Host": "api.cn.ronghub.com",
            "App-Key": rongcloudAppKey,
            "Nonce": nonce,
            "Timestamp": timestamp,
            "Signature": signature,
            "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
            values: postData
        }
    }, function (ret, err) {
        if (true) {
            loadingQueue--;

            if (loadingQueue <= 0) {
                loadingQueue = 0;

                $.myLoading("hide");
            }
        }

        // 请求成功
        if (isObject(ret)) {
            func(ret, null);

            // 请求失败
        } else {
            toast(err.msg);

            func(null, err);
        }
    });
}

/**
 *
 * 获取图片。
 *
 * @param width 图片的宽
 * @param height 图片的高
 * @param sourceType 资源类型  library  or  camera
 * @param func 回调函数
 *
 */
function getPicture(width, height, sourceType, func) {
    if (isNumber(width) && isNumber(width) && isNotEmpty(sourceType) && isFunction(func)) {
        api.getPicture({
            quality: 100,
            allowEdit: true,
            sourceType: sourceType,
            mediaValue: "pic",
            targetWidth: width,
            targetHeight: height,
            encodingType: "jpg",
            destinationType: "url",
            saveToPhotoAlbum: false
        }, function (ret, err) {
            if (isObject(ret)) {
                func(ret, null);

            } else {
                toast(err.msg);

                func(null, err);
            }
        });
    }
}

/**
 *
 * 获取文件后缀名。
 *
 * @param fileName 文件名称。
 *
 */
function getFileSuffix(fileName) {
    if (isEmpty(fileName) || (fileName.indexOf(".") == -1)) {
        return "";
    }

    return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length).toLowerCase();
}

/**
 * 获取字符串长度
 * @param str
 * @returns {number}
 */
function getstrlength(str) {
    if(str==null||str==""){
        return 0;
    }
    var realLength = 0, len = str.length, charCode = -1;
    for (var i = 0; i < len; i++) {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) realLength += 1;
        else realLength += 1;
    }
    return realLength;
}


/**
 *
 * 保存信息。
 *
 * @param key 键
 * @param value 值
 *
 */
function setTaskType(key, value) {
    if (isEmpty(key) || isNull(value)) {
        return;
    }

    $api.setStorage(key, value);
}

/**
 *
 * 获取信息。
 *
 * @param key 键
 * @return {Object} 值
 *
 */
function getTaskType(key) {
    if (isEmpty(key)) {
        return null;
    }

    return $api.getStorage(key);
}